﻿using Core;
using Core.Domain.Customers;
using Net.Web.Framework.UI.Captcha;
using Net.Web.Models.Customers;
using Services.Authentication;
using Services.Customers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Net.Web.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    public class CustomerController : BaseController
    {
        #region Fields

        private readonly IAuthenticationService _authenticationService;
        private readonly IWorkContext _workContext;
        private readonly IStoreContext _storeContext;
        private readonly ICustomerService _customerService;
        private readonly ICustomerRegistrationService _customerRegistrationService;
        private readonly CustomerSettings _customerSettings;
        private readonly CaptchaSettings _captchaSettings;

        #endregion
        
        #region Con
        public CustomerController(IWorkContext workContext, 
            IStoreContext storeContext,
            ICustomerService customerService,
            ICustomerRegistrationService customerRegistrationService,
            IAuthenticationService authenticationService,
            CustomerSettings customerSettings,
            CaptchaSettings captchaSettings)
        {
        this._workContext = workContext;
            this._storeContext = storeContext;
            this._customerService = customerService;
            this._customerSettings = customerSettings;
            this._captchaSettings = captchaSettings;
            this._customerRegistrationService = customerRegistrationService;
            this._authenticationService = authenticationService;
        }
        #endregion

        #region Register / Login / Logout
        
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="checkoutAsGuest"></param>
        /// <returns></returns>
        public ActionResult Login()
        {
            var model = new LoginModel();
            model.NameMode = _customerSettings.NameMethod;
            model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage;
            return View(model);
        }

        /// <summary>
        /// 登陆Action
        /// </summary>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <param name="captchaValid"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var loginResult = _customerRegistrationService.ValidateCustomer(model.Name, model.Password);
                switch (loginResult)
                {
                    case CustomerLoginResults.Successful:
                        {
                            Customer customer = null; ;//= _customerSettings.UsernamesEnabled ? _customerService.GetCustomerByUsername(model.Username) : _customerService.GetCustomerByEmail(model.Email);
                            if (_customerSettings.NameMethod == RegisterMethod.Name)
                                customer = _customerService.GetCustomerByUsername(model.Name);
                            if (_customerSettings.NameMethod == RegisterMethod.Email)
                                customer = _customerService.GetCustomerByEmail(model.Name);
                            if (_customerSettings.NameMethod == RegisterMethod.Phone)
                                customer = _customerService.GetCustomerByPhone(model.Name);

                            _authenticationService.SignIn(customer, model.RememberMe);

                            return RedirectToRoute("HomePage");
                        }
                    case CustomerLoginResults.CustomerNotExist:
                        ModelState.AddModelError("","没有找到该用户");
                        break;
                    case CustomerLoginResults.Deleted:
                        ModelState.AddModelError("", "用户已注销,请联系客服");
                        break;
                    case CustomerLoginResults.NotActive:
                        ModelState.AddModelError("", "用户未激活,请激活后在进行登录");
                        break;
                    case CustomerLoginResults.NotRegistered:
                        ModelState.AddModelError("", "该用户未注册");
                        break;
                    case CustomerLoginResults.WrongPassword:
                    default:
                        ModelState.AddModelError("","您输入的密码错误");
                        break;
                }
            }

            model.NameMode = _customerSettings.NameMethod;
            model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage;
            return View(model);
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            if (_workContext.CurrentCustomer.IsRegistered())
                return RedirectToRoute("HomePage");

            RegisterDetailModel model = new RegisterDetailModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Register(RegisterDetailModel model,string returnUrl,FormCollection from)
        {
            var customer = _workContext.CurrentCustomer;
            if (ModelState.IsValid)
            {
                if (model.UserName != null)
                {
                    model.UserName = model.UserName.Trim();
                }
                var registrationRequest = new CustomerRegistrationRequest(customer, model.UserName, model.UserPassword, model.Email, _customerSettings.NameMethod);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);                
                if (registrationResult.Success)
                {
                    _authenticationService.SignIn(customer, true);
                    
                    return RedirectToRoute("HomePage");
                }
                else
                {
                    foreach (var message in registrationResult.Errors)
                        model.Error += message;
                }
            }

            return View(model);
                                    
        
        }
        #endregion

    }
}